package main

import (
	"fmt"
	"github.com/julienschmidt/httprouter"
	"log"
	"net/http"
)

/**
使用httpRouter路由包
*/

func main() {
	router := httprouter.New()
	router.GET("/", Index)

	//restful
	router.GET("/default", func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
		writer.Write([]byte("default get"))
	})

	router.POST("/default", func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
		writer.Write([]byte("default post"))
	})

	//精确匹配模式
	router.GET("/user/name", func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
		writer.Write([]byte("user name:" + params.ByName("name")))
	})

	//匹配所有
	//router.GET("/user/*name", func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
	//	writer.Write([]byte("user name:" + params.ByName("name")))
	//})

	//使用ServerFiler()访问静态文件
	router.ServeFiles("/static/*filepath", http.Dir("./files"))

	log.Fatal(http.ListenAndServe(":8082", router))

	//捕获异常
	router.PanicHandler = func(writer http.ResponseWriter, request *http.Request, v interface{}) {
		writer.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(writer, "error:%s", v)
	}
}

func Index(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
	writer.Write([]byte("Index"))
}
